package com.kazimsoylu.jpa.service.persistence.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;

import com.kazimsoylu.jpa.service.persistence.EntityService;


@Service
public class EntityServiceImpl implements EntityService 
{
	private EntityManager entityManager;	
	
	public <T> T getEntity( Class<T> clazz, Long id) 
	{		
		return entityManager.find( clazz , id);
	}
	
	public <T> T getEntity( Class<T> clazz, Integer id) 
	{		
		return entityManager.find( clazz , id);
	}
	
	@SuppressWarnings("unchecked")
	public <T> List<T> getEntities(Class<T> clazz) 
	{
		return entityManager.createQuery("from "+clazz.getName()).getResultList();		
	}
	
	@Override
	public <T> List<T> getByNamedQuery(String namedQuery,Object... params) 
	{
		Query query = entityManager.createNamedQuery( namedQuery );
		int numberOfParams = params.length;
		
		for( int i=0;i<numberOfParams; i++ )
		{
			query.setParameter( i+1 , params[i]);
		}
		
		return query.getResultList();	
	}
	
	public EntityManager getEntityManager() {
		return entityManager;
	}

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

}
